# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: donggu

from experimental.prophet.graph import graph
from coin.exchange.kr_rest.product_holders import get_holder_from_product


def proto_from_fastfeed(fastfeed, ticksize=None, raw_ticksize=None, approx_price=None, **kwargs):
  cache = graph.get_aux_entry('proto_from_fastfeed')
  key = '%s|%s|%s|%s|%s' % (
      fastfeed._product.full_symbol, ticksize, raw_ticksize, approx_price, str(kwargs))

  if key not in cache:
    if ticksize is None:
      info = get_holder_from_product(fastfeed._product).product_info
      tick = info.gen_tick()
      if hasattr(tick, 'tick_size'):
        ticksize = tick.tick_size
        raw_ticksize = ticksize * info.price_precision
      elif approx_price is not None:
        price = tick.round(approx_price)
        ticksize = tick.get_next_price(price) - price
        raw_ticksize = ticksize * info.price_precision
      else:
        raise RuntimeError('cannot infer ticksize. provide one.')

    with graph.control_if(None):
      cache[key] = graph.create_node(
          'fastfeed.ProtoFeed', [fastfeed.book, fastfeed.trade, fastfeed.instrument],
          attrs={
              'ticksize': ticksize,
              'raw_ticksize': raw_ticksize,
              'exchange.symbol': '%s.%s' % (fastfeed._product.exchange, fastfeed._product.symbol),
          }).outputs.proto

  return cache[key]
